import { showNotification, showAlert, showUrgent, showNotificationWithAction, NOTIFICATION_TYPES, NOTIFICATION_MESSAGES } from './notification.jsx';

class WebSocketManager {
  constructor() {
    this.ws = null;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectInterval = 3000;
    this.heartbeatInterval = null;
    this.isConnected = false;
    this.listeners = new Map();
    this.url = import.meta.env.VITE_WS_URL || 'ws://localhost:8088/ws/warning';
  }

  // 连接WebSocket
  connect() {
    try {
      // 检查是否支持WebSocket
      if (typeof WebSocket === 'undefined') {
        console.warn('浏览器不支持WebSocket');
        return;
      }

      // 如果已经有连接，先断开
      if (this.ws) {
        this.disconnect();
      }
      
      console.log('正在连接WebSocket:', this.url);
      this.ws = new WebSocket(this.url);
      
      this.ws.onopen = () => {
        console.log('WebSocket连接已建立');
        this.isConnected = true;
        this.reconnectAttempts = 0;
        this.startHeartbeat();
        this.notifyListeners('connected', {});
        showNotification(
          NOTIFICATION_TYPES.SUCCESS,
          '连接成功',
          'WebSocket连接已建立'
        );
      };

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          this.handleMessage(data);
        } catch (error) {
          console.error('解析WebSocket消息失败:', error);
        }
      };

      this.ws.onclose = (event) => {
        console.log('WebSocket连接已关闭:', event.code, event.reason);
        this.isConnected = false;
        this.stopHeartbeat();
        this.notifyListeners('disconnected', { code: event.code, reason: event.reason });
        
        // 根据关闭代码提供更详细的错误信息
        let errorMessage = '';
        switch (event.code) {
          case 1000:
            errorMessage = '正常关闭';
            break;
          case 1001:
            errorMessage = '端点离开';
            break;
          case 1002:
            errorMessage = '协议错误';
            break;
          case 1003:
            errorMessage = '不支持的数据类型';
            break;
          case 1006:
            errorMessage = '连接异常关闭（可能是网络问题或服务器不可用）';
            break;
          case 1007:
            errorMessage = '数据格式错误';
            break;
          case 1008:
            errorMessage = '违反策略';
            break;
          case 1009:
            errorMessage = '消息过大';
            break;
          case 1010:
            errorMessage = '缺少扩展';
            break;
          case 1011:
            errorMessage = '服务器错误';
            break;
          case 1015:
            errorMessage = 'TLS握手失败';
            break;
          default:
            errorMessage = `未知错误 (${event.code})`;
        }
        
        console.log('关闭原因:', errorMessage);
        
        if (!event.wasClean && this.reconnectAttempts < this.maxReconnectAttempts) {
          this.reconnect();
        } else if (event.code === 1006) {
          console.log('建议检查：');
          console.log('1. 后端服务是否正在运行');
          console.log('2. WebSocket服务是否已启动');
          console.log('3. 网络连接是否正常');
          console.log('4. 防火墙是否阻止了连接');
        }
      };

      this.ws.onerror = (error) => {
        console.error('WebSocket连接错误:', error);
        console.log('请确保后端WebSocket服务正在运行在端口8088');
        this.notifyListeners('error', error);
      };

    } catch (error) {
      console.error('创建WebSocket连接失败:', error);
      this.reconnect();
    }
  }

  // 处理接收到的消息
  handleMessage(data) {
    const { type, payload } = data;
    
    switch (type) {
      case 'notification':
        this.handleNotification(payload);
        break;
      case 'approval':
        this.handleApprovalNotification(payload);
        break;
      case 'attendance':
        this.handleAttendanceNotification(payload);
        break;
      case 'project':
        this.handleProjectNotification(payload);
        break;
      case 'system':
        this.handleSystemNotification(payload);
        break;
      case 'alert':
        this.handleAlertNotification(payload);
        break;
      case 'urgent':
        this.handleUrgentNotification(payload);
        break;
      default:
        console.log('未知消息类型:', type, payload);
    }

    // 通知所有监听器
    this.notifyListeners(type, payload);
  }

  // 处理通知消息
  handleNotification(payload) {
    const { level, title, message, actions } = payload;
    
    if (actions && actions.length > 0) {
      showNotificationWithAction(level, title, message, actions);
    } else {
      showNotification(level, title, message);
    }
  }

  // 处理审批通知
  handleApprovalNotification(payload) {
    const { action, title, description, id } = payload;
    
    let message = '';
    let level = NOTIFICATION_TYPES.INFO;
    
    switch (action) {
      case 'pending':
        message = NOTIFICATION_MESSAGES.APPROVAL_PENDING;
        level = NOTIFICATION_TYPES.WARNING;
        break;
      case 'approved':
        message = NOTIFICATION_MESSAGES.APPROVAL_APPROVED;
        level = NOTIFICATION_TYPES.SUCCESS;
        break;
      case 'rejected':
        message = NOTIFICATION_MESSAGES.APPROVAL_REJECTED;
        level = NOTIFICATION_TYPES.ERROR;
        break;
    }

    showNotification(level, message, description);
  }

  // 处理考勤通知
  handleAttendanceNotification(payload) {
    const { action, message } = payload;
    
    switch (action) {
      case 'reminder':
        showNotification(NOTIFICATION_TYPES.WARNING, NOTIFICATION_MESSAGES.ATTENDANCE_REMINDER);
        break;
      case 'submitted':
        showNotification(NOTIFICATION_TYPES.SUCCESS, NOTIFICATION_MESSAGES.ATTENDANCE_SUBMITTED);
        break;
    }
  }

  // 处理项目通知
  handleProjectNotification(payload) {
    const { action, projectName, deadline } = payload;
    
    switch (action) {
      case 'assigned':
        showNotification(
          NOTIFICATION_TYPES.INFO,
          NOTIFICATION_MESSAGES.PROJECT_ASSIGNED,
          `项目: ${projectName}`
        );
        break;
      case 'deadline':
        showNotification(
          NOTIFICATION_TYPES.WARNING,
          NOTIFICATION_MESSAGES.PROJECT_DEADLINE,
          `项目: ${projectName}, 截止时间: ${deadline}`
        );
        break;
    }
  }

  // 处理系统通知
  handleSystemNotification(payload) {
    const { type, message, description } = payload;
    
    switch (type) {
      case 'maintenance':
        showNotification(NOTIFICATION_TYPES.WARNING, NOTIFICATION_MESSAGES.SYSTEM_MAINTENANCE, description);
        break;
      case 'update':
        showNotification(NOTIFICATION_TYPES.INFO, NOTIFICATION_MESSAGES.SYSTEM_UPDATE, description);
        break;
    }
  }

  // 处理预警通知
  handleAlertNotification(payload) {
    const { alertType, title, message, description, data, actions } = payload;
    
    let alertMessage = message || title;
    let alertDescription = description;
    
    // 根据预警类型设置特定的消息
    switch (alertType) {
      case 'budget_exceed':
        alertMessage = NOTIFICATION_MESSAGES.ALERT_BUDGET_EXCEED;
        alertDescription = `项目: ${data?.projectName || '未知项目'}, 超支金额: ¥${data?.exceedAmount || 0}`;
        break;
      case 'deadline_approaching':
        alertMessage = NOTIFICATION_MESSAGES.ALERT_DEADLINE_APPROACHING;
        alertDescription = `项目: ${data?.projectName || '未知项目'}, 剩余天数: ${data?.remainingDays || 0}天`;
        break;
      case 'attendance_abnormal':
        alertMessage = NOTIFICATION_MESSAGES.ALERT_ATTENDANCE_ABNORMAL;
        alertDescription = `员工: ${data?.employeeName || '未知员工'}, 异常类型: ${data?.abnormalType || '未知'}`;
        break;
      case 'contract_expiring':
        alertMessage = NOTIFICATION_MESSAGES.ALERT_CONTRACT_EXPIRING;
        alertDescription = `合同: ${data?.contractName || '未知合同'}, 到期时间: ${data?.expiryDate || '未知'}`;
        break;
      case 'payment_overdue':
        alertMessage = NOTIFICATION_MESSAGES.ALERT_PAYMENT_OVERDUE;
        alertDescription = `付款项目: ${data?.paymentItem || '未知'}, 逾期金额: ¥${data?.overdueAmount || 0}`;
        break;
      case 'system_error':
        alertMessage = NOTIFICATION_MESSAGES.ALERT_SYSTEM_ERROR;
        alertDescription = `错误代码: ${data?.errorCode || '未知'}, 模块: ${data?.module || '未知'}`;
        break;
      case 'data_backup':
        alertMessage = NOTIFICATION_MESSAGES.ALERT_DATA_BACKUP;
        alertDescription = `备份状态: ${data?.backupStatus || '未知'}, 最后备份: ${data?.lastBackup || '未知'}`;
        break;
      case 'security_threat':
        alertMessage = NOTIFICATION_MESSAGES.ALERT_SECURITY_THREAT;
        alertDescription = `威胁类型: ${data?.threatType || '未知'}, 风险等级: ${data?.riskLevel || '未知'}`;
        break;
      case 'performance_issue':
        alertMessage = NOTIFICATION_MESSAGES.ALERT_PERFORMANCE_ISSUE;
        alertDescription = `性能指标: ${data?.metric || '未知'}, 当前值: ${data?.currentValue || '未知'}`;
        break;
      case 'resource_shortage':
        alertMessage = NOTIFICATION_MESSAGES.ALERT_RESOURCE_SHORTAGE;
        alertDescription = `资源类型: ${data?.resourceType || '未知'}, 剩余量: ${data?.remainingAmount || '未知'}`;
        break;
      default:
        alertMessage = alertMessage || '系统预警';
        break;
    }

    // 如果有操作按钮，使用带操作的通知
    if (actions && actions.length > 0) {
      showNotificationWithAction(NOTIFICATION_TYPES.ALERT, alertMessage, alertDescription, actions);
    } else {
      showAlert(alertMessage, alertDescription);
    }
  }

  // 处理紧急通知
  handleUrgentNotification(payload) {
    const { urgentType, title, message, description, data, actions } = payload;
    
    let urgentMessage = message || title;
    let urgentDescription = description;
    
    // 根据紧急类型设置特定的消息
    switch (urgentType) {
      case 'system_down':
        urgentMessage = NOTIFICATION_MESSAGES.URGENT_SYSTEM_DOWN;
        urgentDescription = `影响范围: ${data?.affectedServices || '全部服务'}, 预计恢复时间: ${data?.estimatedRecovery || '未知'}`;
        break;
      case 'data_loss':
        urgentMessage = NOTIFICATION_MESSAGES.URGENT_DATA_LOSS;
        urgentDescription = `数据范围: ${data?.dataScope || '未知'}, 损失程度: ${data?.lossLevel || '未知'}`;
        break;
      case 'security_breach':
        urgentMessage = NOTIFICATION_MESSAGES.URGENT_SECURITY_BREACH;
        urgentDescription = `漏洞类型: ${data?.breachType || '未知'}, 影响等级: ${data?.impactLevel || '未知'}`;
        break;
      case 'critical_error':
        urgentMessage = NOTIFICATION_MESSAGES.URGENT_CRITICAL_ERROR;
        urgentDescription = `错误模块: ${data?.errorModule || '未知'}, 错误级别: ${data?.errorLevel || '未知'}`;
        break;
      default:
        urgentMessage = urgentMessage || '紧急通知';
        break;
    }

    // 紧急通知通常需要操作按钮
    if (actions && actions.length > 0) {
      showNotificationWithAction(NOTIFICATION_TYPES.URGENT, urgentMessage, urgentDescription, actions);
    } else {
      showUrgent(urgentMessage, urgentDescription);
    }
  }

  // 发送消息
  send(type, payload) {
    if (this.isConnected && this.ws) {
      const message = JSON.stringify({ type, payload, timestamp: Date.now() });
      this.ws.send(message);
    } else {
      console.warn('WebSocket未连接，无法发送消息');
    }
  }

  // 重连
  reconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('WebSocket重连次数已达上限');
      console.log('请检查后端服务是否正在运行，端口是否正确');
      showNotification(
        NOTIFICATION_TYPES.ERROR,
        '连接失败',
        'WebSocket连接失败，请检查后端服务是否正在运行'
      );
      return;
    }

    this.reconnectAttempts++;
    console.log(`WebSocket重连中... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
    console.log(`尝试连接到: ${this.url}`);
    
    setTimeout(() => {
      this.connect();
    }, this.reconnectInterval);
  }

  // 开始心跳
  startHeartbeat() {
    this.heartbeatInterval = setInterval(() => {
      if (this.isConnected) {
        this.send('ping', {});
      }
    }, 30000); // 30秒发送一次心跳
  }

  // 停止心跳
  stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval);
      this.heartbeatInterval = null;
    }
  }

  // 添加消息监听器
  addListener(type, callback) {
    if (!this.listeners.has(type)) {
      this.listeners.set(type, []);
    }
    this.listeners.get(type).push(callback);
  }

  // 移除消息监听器
  removeListener(type, callback) {
    if (this.listeners.has(type)) {
      const callbacks = this.listeners.get(type);
      const index = callbacks.indexOf(callback);
      if (index > -1) {
        callbacks.splice(index, 1);
      }
    }
  }

  // 通知所有监听器
  notifyListeners(type, payload) {
    if (this.listeners.has(type)) {
      this.listeners.get(type).forEach(callback => {
        try {
          callback(payload);
        } catch (error) {
          console.error('监听器执行错误:', error);
        }
      });
    }
  }

  // 断开连接
  disconnect() {
    this.stopHeartbeat();
    if (this.ws) {
      this.ws.close(1000, '主动断开连接');
      this.ws = null;
    }
    this.isConnected = false;
  }

  // 获取连接状态
  getConnectionStatus() {
    return {
      isConnected: this.isConnected,
      reconnectAttempts: this.reconnectAttempts,
      url: this.url
    };
  }
}

// 创建单例实例
const wsManager = new WebSocketManager();

export default wsManager;
